from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission as DjangoPermission, Group as DjangoGroup
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model
from apps.permissions.models import PermissionCategory, PermissionExtension, RoleExtension, UserRoleAssignment

User = get_user_model()


class Command(BaseCommand):
    help = '初始化权限系统数据'

    def add_arguments(self, parser):
        parser.add_argument(
            '--reset',
            action='store_true',
            help='重置所有权限数据',
        )

    def handle(self, *args, **options):
        if options['reset']:
            self.stdout.write('正在重置权限数据...')
            self.reset_permissions()
        
        self.stdout.write('正在初始化权限数据...')
        self.init_permission_categories()
        self.init_system_roles()
        self.init_admin_user()
        self.update_permission_extensions()
        
        self.stdout.write(
            self.style.SUCCESS('权限系统初始化完成！')
        )

    def reset_permissions(self):
        """重置权限数据"""
        UserRoleAssignment.objects.all().delete()
        RoleExtension.objects.all().delete()
        PermissionExtension.objects.all().delete()
        PermissionCategory.objects.all().delete()
        
        # 删除自定义组，保留Django默认权限
        DjangoGroup.objects.exclude(name__in=['admin', 'staff']).delete()
        
        self.stdout.write('权限数据已重置')

    def init_permission_categories(self):
        """初始化权限分类"""
        categories = [
            {'name': '用户管理', 'code': 'user_management', 'sort_order': 1},
            {'name': '权限管理', 'code': 'permission_management', 'sort_order': 2},
            {'name': '系统管理', 'code': 'system_management', 'sort_order': 3},
            {'name': '内容管理', 'code': 'content_management', 'sort_order': 4},
            {'name': '数据分析', 'code': 'data_analysis', 'sort_order': 5},
        ]
        
        for cat_data in categories:
            category, created = PermissionCategory.objects.get_or_create(
                code=cat_data['code'],
                defaults=cat_data
            )
            if created:
                self.stdout.write(f'创建权限分类: {category.name}')

    def init_system_roles(self):
        """初始化系统角色"""
        roles_data = [
            {
                'name': '超级管理员',
                'code': 'super_admin',
                'description': '拥有系统所有权限的超级管理员',
                'is_system': True,
                'level': 1
            },
            {
                'name': '系统管理员',
                'code': 'system_admin',
                'description': '负责系统配置和用户管理的管理员',
                'is_system': True,
                'level': 2
            },
            {
                'name': '普通用户',
                'code': 'normal_user',
                'description': '系统的普通用户，拥有基本功能权限',
                'is_system': True,
                'level': 10
            },
        ]
        
        for role_data in roles_data:
            # 创建Django组
            group, group_created = DjangoGroup.objects.get_or_create(
                name=role_data['name']
            )
            
            # 创建角色扩展
            role_ext, role_created = RoleExtension.objects.get_or_create(
                group=group,
                defaults={
                    'code': role_data['code'],
                    'description': role_data['description'],
                    'is_system': role_data['is_system'],
                    'level': role_data['level'],
                    'status': 'active'
                }
            )
            
            if role_created:
                self.stdout.write(f'创建系统角色: {role_ext.name}')
                
                # 为超级管理员分配所有权限
                if role_data['code'] == 'super_admin':
                    all_permissions = DjangoPermission.objects.all()
                    group.permissions.set(all_permissions)
                    self.stdout.write(f'为 {role_ext.name} 分配了 {all_permissions.count()} 个权限')

    def init_admin_user(self):
        """初始化管理员用户"""
        try:
            admin_user = User.objects.get(email='admin@example.com')
            self.stdout.write('管理员用户已存在')
        except User.DoesNotExist:
            admin_user = User.objects.create_superuser(
                username='admin',
                email='admin@example.com',
                password='admin123',
                real_name='系统管理员'
            )
            self.stdout.write('创建管理员用户: admin@example.com')
        
        # 分配超级管理员角色
        try:
            super_admin_role = RoleExtension.objects.get(code='super_admin')
            assignment, created = UserRoleAssignment.objects.get_or_create(
                user=admin_user,
                role=super_admin_role,
                defaults={
                    'status': 'active',
                    'reason': '系统初始化自动分配'
                }
            )
            
            # 同时添加到Django组
            admin_user.groups.add(super_admin_role.group)
            
            if created:
                self.stdout.write(f'为用户 {admin_user.username} 分配超级管理员角色')
            
        except RoleExtension.DoesNotExist:
            self.stdout.write(
                self.style.WARNING('超级管理员角色不存在，请先运行角色初始化')
            )

    def update_permission_extensions(self):
        """更新权限扩展信息"""
        # 为所有Django权限创建扩展信息
        permissions_without_extension = DjangoPermission.objects.filter(
            permissionextension__isnull=True
        )

        user_mgmt_category = PermissionCategory.objects.get(code='user_management')
        perm_mgmt_category = PermissionCategory.objects.get(code='permission_management')
        system_mgmt_category = PermissionCategory.objects.get(code='system_management')

        for perm in permissions_without_extension:
            # 根据应用和模型确定分类
            app_label = perm.content_type.app_label
            model_name = perm.content_type.model

            if app_label == 'authentication':
                category = user_mgmt_category
            elif app_label == 'permissions':
                category = perm_mgmt_category
            else:
                category = system_mgmt_category

            # 创建权限扩展
            PermissionExtension.objects.create(
                permission=perm,
                category=category,
                module=app_label,
                resource_path=f'/{app_label}/{model_name}/',
                api_endpoint=f'/api/{app_label}/{model_name}/',
                description=perm.name,
                status='active'
            )

        self.stdout.write(f'更新了 {permissions_without_extension.count()} 个权限扩展')
